#!/usr/bin/perl
use Getopt::Std;
getopt("s:m:r:w:e:d", \%args); 
my $sample = $args{s};
my $marker= $args{m};
my $reference= $args{r};
my $window = $args{w};
my $edge = $args{e};
my $maindir = $args{d};
chomp $sample;
chomp $marker;
chomp $reference;
chomp $window;
chomp $edge;
chomp $maindir;
print $maindir."\n";
@mar =split(/\//,$maindir);
pop(@mar);
pop(@mar);
$dir_bin = join("/",@mar);

if($sample eq "")
{
	die "entered samplefile name  is empty\n";
	
}
if($marker eq "")
{
        die "entered markerfile name  is empty\n";

}
if($reference eq "")
{
        die "entered referencefile name is empty\n";

}
if($window eq "")
{
        die "entered window size is empty\n";

}
if($edge eq "")
{
        die "entered edge name is empty\n";

}

print "Sample : $sample Marker : $marker Reference: $reference Windowsize : $window Edges : $edge\n";


open BUFF,"<$marker" or die "Can't open $sample : $!";
$n = 1;
while($line = <BUFF>)
{
	chomp $line;
	@array = split(" ",$line);
	$array_coord[$n] = $array[1];
	$n++;
}
@sorted_array_coord = sort { $a <=> $b } @array_coord;
$min = $sorted_array_coord[1];
$max = $sorted_array_coord[@sorted_array_coord-1];
print "Max $max Min $min\n";
my $segment =  sprintf("%d", ($max-$min)/$window);
if($segment < ($max-$min)/$window)
{
	$segment++;
}
#printf "%d\n", 3.1415126;
#print "Number of Segments : $segment\n";
for($i=0;$i<$segment;$i++)
{
	$lowlimit = $min+$window*($i);
	$segment_array_min[$i] =$lowlimit-$edge; 
	$temp = $i+1;
	#print "Segment Min ".$temp." : ".$lowlimit."\n";
	$lowlimit_ar[$i] = $lowlimit;
	$uplimit = $min+$window*($i+1);
	$segment_array_max[$i] =$uplimit+$edge; 
	$uplimit_ar[$i] = $uplimit;
	#print "Segment Max ".$temp." : ".$uplimit."\n";
}
#print "@segment_array_min\n";
#print "@segment_array_max\n";
#print "@lowlimit_ar\n@uplimit_ar\n@segment_array_min\n@segment_array_max\n";
#print "after\n";
$uplimit_ar[@uplimit_ar -1] = $max+1;
$segment_array_max[@segment_array_max-1] = $max+1;
$lowlimit_ar[0] =$min-1;	
$segment_array_min[0] = $min-1;
if($segment > 1)
{
	if(($max - $lowlimit_ar[@lowlimit-1])<$window/2)
	{
		pop(@lowlimit_ar);
		pop(@uplimit_ar);
		$uplimit_ar[@uplimit_ar -1] = $max;
		pop(@segment_array_min);
		pop(@segment_array_max);
		$segment_array_max[@segment_array_max-1] = $max+1;
#		print "@lowlimit_ar\n@uplimit_ar\n@segment_array_min\n@segment_array_max\n";

	}
}
$segment = @lowlimit_ar;
for($i=0;$i<$segment;$i++)
{
        $num1m{$i}=0;

}

open BUFF,"<$marker" or die "Can't open $sample : $!";
while($line = <BUFF>)
{
        chomp $line;
        @array = split(" ",$line);
        for($i=0;$i<$segment;$i++)
        {
                if($array[1] > $segment_array_min[$i] && $array[1] < $segment_array_max[$i])
                {
                        #${"array".$i}[$num{$i}] = $array[0];
                        $num1m{$i}++;
                        $hash1m{$array[0]} = $i;
			
                }
        }
}
for($i=0;$i<$segment;$i++)
{
        $num1s{$i}=0;

}

open BUFF,"<$sample" or die "Can't open $sample : $!";
$line1 = <BUFF>;
$line2 = <BUFF>;
while($line = <BUFF>)
{
        chomp $line;
        @array = split(" ",$line);
        if(exists($hash1m{$array[1]}))
        {
		$num1s{$hash1m{$array[1]}}++;
        }
}
#print "after 2\n";
$temp_buff =0;
for($i=0;$i<$segment;$i++)
{
	
        $array_1[$i] = $num1m{$i};
	$array_2[$i] = $num1s{$i};
	print "$i\t $array_1[$i]\t $array_2[$i]\n";
	if($array_1[$i] == 0 || $array_2[$i] == 0)
	{
		$temp_buff++;
		#$uplimit_ar[$i-1] = $uplimit_ar[$i];
		$segment_array_max[$i-1] = $segment_array_max[$i]; 
		$lowlimit_ar[$i] = 0;
		$uplimit_ar[$i-1] = 0;
		$segment_array_min[$i] = 0;
		$segment_array_max[$i-1] = 0;
	}
}
@lowlimit_ar = sort { $a <=> $b } @lowlimit_ar;
@uplimit_ar = sort { $a <=> $b } @uplimit_ar;
@segment_array_min = sort { $a <=> $b } @segment_array_min;
@segment_array_max = sort { $a <=> $b } @segment_array_max;
#print @lowlimit_ar."\n".@uplimit_ar."\n".@segment_array_min."\n".@segment_array_max."\n";
#print "check0 @lowlimit_ar\n\n@uplimit_ar\n\n@segment_array_min\n\n@segment_array_max\n\n";
for($i=0;$i<$temp_buff;$i++)
{
	shift(@lowlimit_ar);
	shift(@uplimit_ar);
	shift(@segment_array_min);
	shift(@segment_array_max);
	$segment = @segment_array_min;
}
#print @lowlimit_ar."\n".@uplimit_ar."\n".@segment_array_min."\n".@segment_array_max."\n";
#print "check1 @lowlimit_ar\n\n@uplimit_ar\n\n@segment_array_min\n\n@segment_array_max\n\n";
for($i=0;$i<$segment;$i++)
{
        #$lowlimit = $min+$window*($i);
        #$segment_array_min[$i] =$lowlimit-$edge;
        $temp = $i+1;
	print "Segment Min ".$temp." : ".$lowlimit_ar[$i]."\n";
        #$lowlimit_ar[$i] = $lowlimit;
        #$uplimit = $min+$window*($i+1);
        #$segment_array_max[$i] =$uplimit+$edge;
        #$uplimit_ar[$i] = $uplimit;
	print "Segment Max ".$temp." : ".$uplimit_ar[$i]."\n";
}
print "@segment_array_min\n";
print "@segment_array_max\n";

#print " 1 @array_1\n2 @array_2\n";
#print $segment."\n";

open BUFF,"<$marker" or die "Can't open $sample : $!";
for($i=0;$i<$segment;$i++)
{
	$num{$i}=0;	

}
open(WR,">$maindir/no_snp_hapmap.txt");
while($line = <BUFF>)
{
	chomp $line;
        @array = split(" ",$line);
	for($i=0;$i<$segment;$i++)
	{
		if($array[1] > $segment_array_min[$i] && $array[1] < $segment_array_max[$i])
		{
			${"array".$i}[$num{$i}] = $array[0];		
			$num{$i}++;
			$hash{$array[0]} = $i+1;
			
		}	
	}
}

open BUFF,"<$sample" or die "Can't open $sample : $!";
$line1 = <BUFF>;
$line2 = <BUFF>;
for($i=0;$i<$segment;$i++)
{
	$f = $i+1;
	$buff = "BUFF$f";
	$sample=~ s/.bgl/_/g;
        @tempy = split(/\//,$sample);
        $sample = pop(@tempy);
	$file = "$maindir/$f/".$sample."segment$f".".bgl";
	system("mkdir $maindir/$f");
	open($buff,">$file");
	print $buff $line1;
	print $buff $line2;
}
while($line = <BUFF>)
{
	chomp $line;
	@array = split(" ",$line);
	$samplehash{$array[1]} =$line;
	if(exists($hash{$array[1]}))
	{
	#	$num = $hash{$array[1]};
	#	$buff = "BUFF$num";
	#	print $buff $line."\n";
	}
	else
	{
		print WR $line."\n";

	}
}

for($i=0;$i<$segment;$i++)
{
	$f = $i+1;
        $buff = "BUFF$f";
	for($y=0;$y<@{"array".$i};$y++)
	{	if(exists($samplehash{${"array".$i}[$y]}))
		{
		print $buff $samplehash{${"array".$i}[$y]}."\n";
		}
	}
}

open BUFF,"<$reference" or die "Can't open $reference : $!";
$line1 = <BUFF>;
for($i=0;$i<$segment;$i++)
{
        $f = $i+1;
        $buff = "BUFF1$f";
	$reference =~ s/.bgl/_/g;
	@tempy = split(/\//,$reference);
        $reference = pop(@tempy);
        $file = "$maindir/$f/".$reference."segment$f".".bgl";
        open($buff,">$file");
        print $buff $line1;
}
while($line = <BUFF>)
{
        chomp $line;
        @array = split(" ",$line);
	$referencehash{$array[1]} =$line;
      #          $num = $hash{$array[1]};
       #         $buff = "BUFF$num";
        #        print $buff $line."\n";
}
for($i=0;$i<$segment;$i++)
{
        $f = $i+1;
        $buff = "BUFF1$f";
        for($y=0;$y<@{"array".$i};$y++)
        { 
		if(exists($referencehash{${"array".$i}[$y]}))
		{
                print $buff $referencehash{${"array".$i}[$y]}."\n";
		}

        }
}

open BUFF,"<$marker" or die "Can't open $marker : $!";
for($i=0;$i<$segment;$i++)
{
        $f = $i+1;
        $buff = "BUFF2$f";
        $marker =~ s/.txt/_/g;
	@tempy = split(/\//,$marker);
	$marker = pop(@tempy);
        $file = "$maindir/$f/".$marker."segment$f".".txt";
        #print $file."\n";
	open($buff,">$file");
}
while($line = <BUFF>)
{
        chomp $line;
        @array = split(" ",$line);
	$markerhash{$array[0]} =$line;
              #  $num = $hash{$array[0]};
               # $buff = "BUFF$num";
               # print $buff $line."\n";
}
for($i=0;$i<$segment;$i++)
{
        $f = $i+1;
        $buff = "BUFF2$f";
        for($y=0;$y<@{"array".$i};$y++)
        {
		if(exists($markerhash{${"array".$i}[$y]}))
		{
                print $buff $markerhash{${"array".$i}[$y]}."\n";
		}
        }
}
for($i=0;$i<$segment;$i++)
{
	 $f = $i+1;
	 $M_file = "$maindir/$f/".$marker."segment$f".".txt";
	$M1_file = "$maindir/$f/".$marker."segment$f"."1".".txt";
	$M2_file = "$maindir/$f/".$marker."segment$f"."2".".txt";
	 $R_file = "$maindir/$f/".$reference."segment$f".".bgl";
	 $R1_file = "$maindir/$f/".$reference."segment$f"."1".".bgl";
	 $R2_file = "$maindir/$f/".$reference."segment$f"."2".".bgl";
	 $S_file = "$maindir/$f/".$sample."segment$f".".bgl";
	system("/usr/bin/perl /data1/bsi/BORA_processing/devel/data_HTHGU/illumina1/MayoGAP/mayogap_emerge/raw/clean/beagle/run_beagle/beagle_mainrun/workflow/bin/perl_flip_snp_sample_reference.pl -s $S_file -r $R_file -n $R1_file -m $M_file -o $M1_file");
	 system("cp $M_file $M2_file");
	system("cp $R_file $R2_file");
	system("mv $R1_file $R_file");	
	 system("mv $M1_file $M_file");
}
open(BUFF,"/data1/bsi/BORA_processing/devel/data_HTHGU/illumina1/MayoGAP/mayogap_emerge/raw/clean/beagle/run_beagle/beagle_mainrun/workflow/bin/runbeagle_template_research1");
@lines = <BUFF>;
$line = join("",@lines);
@lines1 = split("zzz",$line);
for($i=0;$i<$segment;$i++)
{
        $f = $i+1;
	system("/bin/gzip $maindir/$f/*.*");
	$buff = "BUFF$f";
	@run_bg = split(/\//,$maindir);
	$run_bg = $run_bg[@run_bg -1];
	$file = "$maindir/$f/runbeagle$run_bg_$f";
	open($buff,">$file");
	$work_dir = "$maindir/$f/workdir";
	$geno_gz = "$maindir/$f/geno_segment$f.bgl.gz";
	$marker_gz = "$maindir/$f/markers_segment$f.txt.gz";
	$phased_gz = "$maindir/$f/phased_segment$f.bgl.gz";
	$out_dir = "$maindir/$f/beagle_out_$f";
	$ou_dir =  "$maindir/$f";
	$line = $lines1[0].$ou_dir.$lines1[1].$ou_dir.$lines1[2].$work_dir.$lines1[3].$work_dir.$lines1[4].$work_dir.$lines1[5].$geno_gz.$lines1[6].$marker_gz.$lines1[7].$phased_gz.$lines1[8].$out_dir.$lines1[9].$work_dir.$lines1[10];
	print $buff $line;
	system("qsub $maindir/$f/runbeagle$run_bg_$f");
	#print WRB "qsub $maindir/$f/runbeagle$run_bg_$f\n";
}
